package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.QueryPackageDto;
import com.huaxiafinance.management.dto.request.UpdatePackageDto;
import com.huaxiafinance.management.dto.request.UpdatePackageSortDto;
import com.huaxiafinance.management.mapper.PartnerPackageMapper;
import com.huaxiafinance.management.mapper.UserMapper;
import com.huaxiafinance.management.mapper.YfqImgMapper;
import com.huaxiafinance.management.mapper.YfqLogMapper;
import com.huaxiafinance.management.model.*;
import com.huaxiafinance.management.service.PartnerPackageService;
import com.huaxiafinance.management.util.MessageResult;
import com.huaxiafinance.management.util.UUIDUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/5.
 */
@SuppressWarnings("ALL")
@Service
@Transactional
public class PartnerPackageServiceImpl implements PartnerPackageService{
    private static final Logger logger = Logger.getLogger(PartnerPackageServiceImpl.class);
    @Autowired
    private PartnerPackageMapper partnerPackageMapper;
    @Autowired
    private YfqImgMapper yfqImgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private YfqLogMapper yfqLogMapper;

    /**
     * 套餐列表
     * @param dto
     * @return
     */
    @Override
    public MessageResult getPackageList(QueryPackageDto dto) {
        MessageResult result = new MessageResult();
        try {
            dto.setPage(dto.getPage() == null ? null:(dto.getPage()) * dto.getRows());
            List<PartnerPackage> packages = partnerPackageMapper.getPackageList(dto);
            Integer rows = partnerPackageMapper.getPackageCount(dto);
            result.setSuccessResult();
            result.setData(packages);
            result.setRows(rows);
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        result.setFailureResult();
        return result;
    }

    /**
     * 添加或修改套餐
     * @param dto
     * @return
     */
    @Override
    public MessageResult updatePackage(UpdatePackageDto dto) {
        MessageResult result = new MessageResult();
        PartnerPackageWithBLOBs vo = getPackage(dto);
        //选择套餐图片
        List<String> opPackageImgs = dto.getOpPackageImgs();
        //套餐描述图片
        List<String>packageDescImgs = dto.getPackageDescImgs();
        //附加内容图片
        List<String>addtionalImgs = dto.getAddtionalImgs();
        vo.setAddtionalImgs(addtionalImgs);
        vo.setId(dto.getId());
        Map<String,Object> data = new HashMap<>();
        if(dto.getId()==null){
            //创建人
            User creator = userMapper.selectById(dto.getAdminId());
            data.put("creatorName",creator.getName());
            data.put("gmtCreate",vo.getGmtCreate());
            int maxSort = partnerPackageMapper.getMaxSort();
            String packageUuid = UUIDUtil.getUUID();
            vo.setPackageUuid(packageUuid);
            vo.setSort(maxSort+1);
            partnerPackageMapper.insertSelective(vo);
            //插入可选择套餐图片
            if(opPackageImgs!=null){
                insertImg(opPackageImgs,packageUuid, CommonConstant.OPTIONAL_PACKAGE_IMG);
            }
            //插入套餐描述图片
            if(packageDescImgs!=null){
                insertImg(packageDescImgs,packageUuid,CommonConstant.PACKAGE_DESCRIPTION_IMG);
            }
            //插入附加图片
            if(addtionalImgs!=null){
                insertImg(addtionalImgs,packageUuid,CommonConstant.PACKAGE_ADDTIONAL_IMG);
            }
            insertLog(dto.getAdminId(),"添加了套餐 packageUUid="+packageUuid);
        }else {
            PartnerPackageWithBLOBs partnerPackage = partnerPackageMapper.selectByPrimaryKey(dto.getId());
            //修改人
            User modifier = userMapper.selectById(dto.getAdminId());
            data.put("modifierName",modifier.getName());
            data.put("gmtModified",vo.getGmtModified());
            //创建人
            User creator = userMapper.selectById(partnerPackage.getCreater());
            data.put("creatorName",creator.getName());
            data.put("gtmCreate",partnerPackage.getGmtCreate());
            vo.setGmtCreate(partnerPackage.getGmtCreate());
            vo.setCreater(partnerPackage.getCreater());
            vo.setModifier(dto.getAdminId());
            vo.setGmtModified(new Date());
            partnerPackageMapper.updateByPrimaryKeySelective(vo);
            String packageUuid = dto.getPackageUuid();
            yfqImgMapper.deletePackageImgs(packageUuid);
            //插入可选择套餐图片
            if(opPackageImgs!=null){
                insertImg(opPackageImgs,packageUuid,CommonConstant.OPTIONAL_PACKAGE_IMG);
            }
            //插入套餐描述图片
            if(packageDescImgs!=null){
                insertImg(packageDescImgs,packageUuid,CommonConstant.PACKAGE_DESCRIPTION_IMG);
            }
            //插入附加图片
            if(addtionalImgs!=null){
                insertImg(addtionalImgs,packageUuid,CommonConstant.PACKAGE_ADDTIONAL_IMG);
            }
            insertLog(dto.getAdminId(),"修改了套餐 id="+dto.getId());
        }
        result.setData(data);
        result.setSuccessResult();
        return result;
    }

    /**
     * 套餐详情
     * @param id
     * @return
     */
    @Override
    public MessageResult getPackageDetail(Integer id) {
        MessageResult result = new MessageResult();
        try {
            PartnerPackage partnerPackage = partnerPackageMapper.getPackageDetail(id);
            String packageUuid = partnerPackage.getPackageUuid();
            //可选套餐图片
            List<String> opPackageImgs = yfqImgMapper.selectPackageImgs(packageUuid,CommonConstant.OPTIONAL_PACKAGE_IMG);
            partnerPackage.setOpPackageImgs(opPackageImgs);
            //套餐描述图片
            List<String>packageDescImgs = yfqImgMapper.selectPackageImgs(packageUuid,CommonConstant.PACKAGE_DESCRIPTION_IMG);
            partnerPackage.setPackageDescImgs(packageDescImgs);
            //附加内容图片
            List<String>addtionalImgs = yfqImgMapper.selectPackageImgs(packageUuid,CommonConstant.PACKAGE_ADDTIONAL_IMG);
            partnerPackage.setAddtionalImgs(addtionalImgs);
            //创建人
            User creator = userMapper.selectById(partnerPackage.getCreater());
            partnerPackage.setCreatorName(creator.getName());
            Integer adminId = partnerPackage.getModifier();
            if(adminId !=null){
                User modifier = userMapper.selectById(adminId);
                partnerPackage.setModifierName(modifier.getName());
            }
            result.setData(partnerPackage);
            result.setSuccessResult();
            return result;
        }catch (Exception e){
            logger.info(e.getMessage());
        }
        result.setFailureResult();
        partnerPackageMapper.selectByPrimaryKey(id);
        return result;
    }

    /**
     * 套餐排序
     * @param dto
     * @return
     */
    @Override
    public boolean changeSort(UpdatePackageSortDto dto) {
        //新顺序集合
        List<PartnerPackageWithBLOBs> list = dto.getPackageList();
        if(list != null && list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                PartnerPackageWithBLOBs temp = new PartnerPackageWithBLOBs();
                temp.setId(list.get(i).getId());
                temp.setSort(list.get(i).getSort());
                temp.setModifier(dto.getAdminId());
                temp.setGmtModified(new Date());
                if(list.get(i).getId() != null && list.get(i).getSort() != null){
                    partnerPackageMapper.updateByPrimaryKeySelective(temp);
                }
            }
        }
        insertLog(dto.getAdminId(),"修改了套餐的排序");
        return true;
    }

    /**
     *
     * @param id 套餐id
     * @param isEnable 1启用 0禁用
     * @param adminId  操作人id
     * @return
     */
    @Override
    public MessageResult updateStatus(Integer id,Integer isEnable,Integer adminId) {
        MessageResult result = new MessageResult();
        PartnerPackageWithBLOBs partnerPackage = partnerPackageMapper.selectByPrimaryKey(id);
        String pType = partnerPackage.getpType();
        if("Z".equals(pType) && isEnable==1){
            //将启用的通用
            partnerPackageMapper.updateStatus(0,null,adminId);
            //将现在的启用
            partnerPackageMapper.updateStatus(isEnable,id,adminId);
        }else {
            partnerPackage.setIsEnable(isEnable);
            partnerPackage.setModifier(adminId);
            partnerPackage.setGmtModified(new Date());
            partnerPackageMapper.updateByPrimaryKeySelective(partnerPackage);
        }
        insertLog(adminId,"修改了套餐的启用状态 id="+id);
        result.setSuccessResult();
        return result;
    }

    /**
     * 配置套餐类
     * @param dto
     * @return
     */
    private PartnerPackageWithBLOBs getPackage(UpdatePackageDto dto){
        PartnerPackageWithBLOBs vo = new PartnerPackageWithBLOBs();
        vo.setId(dto.getId());
        vo.setCreater(dto.getAdminId());
        vo.setName(dto.getName());
        vo.setpType(dto.getpType());
        vo.setPrice(new BigDecimal(dto.getPrice()));
        vo.setIsEnable(0);
        vo.setSort(dto.getSort());
        vo.setIsSendGrowthValue(dto.getIsSendGrowthValue());
        vo.setIsGiveScore(dto.getIsGiveScore());
        vo.setIsLimit(dto.getIsLimit());
        vo.setAdditionalTxt(dto.getAdditionalTxt());
        vo.setAvailableTxt(dto.getAvailableTxt());
        vo.setPackageTxt(dto.getPackageTxt());
        vo.setGmtCreate(new Date());
        vo.setCreater(dto.getAdminId());
        vo.setSendScore(dto.getSendScore());
        vo.setPackageUuid(dto.getPackageUuid());
        return vo;
    }

    /**
     * 插入图片
     * @param imgs
     * @param packageUuid
     * @param type
     */
    private void insertImg(List<String>imgs,String packageUuid,Integer type){
        for(int i=0;i<imgs.size();i++){
            YfqImg yfqImg = new YfqImg();
            yfqImg.setId(UUIDUtil.getUUID());
            yfqImg.setSort(i+1);
            yfqImg.setImgUrl(imgs.get(i));
            yfqImg.setCreateAt(new Date());
            yfqImg.setType(type);
            yfqImg.setIsAnshuo(0);
            yfqImg.setTypeParam(packageUuid);
            yfqImgMapper.insert(yfqImg);
        }
    }

    /**
     * 插入合伙人套餐操作日志
     * @param adminid
     * @param message
     */
    private void insertLog(Integer adminid,String message){
        if(adminid == null || message == null){
            return;
        }
        YfqLog log = new YfqLog();
        log.setCreateAt(new Date());
        log.setLogType(CommonConstant.PACKAGE_LOG_TYPE);
        log.setAdminId(adminid);
        log.setMessage(message);
        yfqLogMapper.insert(log);
    }
}
